package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数hibernate检查过了
        //2.根据用户名查询用户信息
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName());
        WmUser wmUser = getOne(wrapper);
        //3.密码加盐和md5加密，与数据库比较是否一致
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (!wmUser.getPassword().equals(pwd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或者密码错误");
        }
        //4.查询用户状态信息
        if (wmUser.getStatus()!=9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //5.颁发jwt令牌
        Map<String,Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        map.put("token",token);
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        map.put("user",wmUserVO);
        //6.将令牌和用户信息封装返回
        return ResponseResult.okResult(map);
    }
}
